const inquirer = require("inquirer");
const { fetchRepoList, fetchTagList } = require("./request");
const { wrapLoading } = require("./util");
const downloadGitRepo = require("download-git-repo");
const util = require("util");
const path = require("path");

class Creator {
  constructor(projectName, targetDir) {
    //new的时候会调用构造函数
    this.name = projectName;
    this.target = targetDir;
    //此时这个方法就是一个promise方法
    this.downloadGitRepo = util.promisify(downloadGitRepo);
  }
  async fetchRepo() {
    //失败重新获取
    let repos = await wrapLoading(fetchRepoList, "waiting fetch template");
    // console.log(repos);s
    if (!repos) {
      return;
    }
    repos = repos.map((item) => item.name);
    let { repo } = await inquirer.prompt({
      name: "repo",
      type: "list",
      choices: repos,
      message: "choose a template to create project",
    });
    return repo;
  }
  async fetchTag(repo) {
    //根据repo拉取版本号
    let tags = await wrapLoading(fetchTagList, "waiting fetch tags", repo);
    if (!tags) {
      return;
    }
    // console.log(tags);
    tags = tags.map((item) => item.name);
    let { tag } = await inquirer.prompt({
      name: "tag",
      type: "list",
      choices: tags,
      message: "choose a tag to create project",
    });
    return tag;
  }
  async download(repo, tag) {
    //需要先拼接出下载路径
    let requestUrl = `zhu-cli/${repo}${tag ? "#" + tag : ""}`;
    //把资源下载到某个路径上(后续可以增加缓存功能)
    //放到系统目录中 模板 和用户的其他选择 生成结果放到当前目录下
    await wrapLoading(
      this.downloadGitRepo,
      `downloading template ${repo}@${tag}`,
      requestUrl,
      path.resolve(process.cwd(), `${repo}@${tag}`)
    );
    return this.target;
  }
  async create() {
    //创建
    //将模板down下来 download-git-repo
    // console.log(this.name);
    // console.log(this.target);
    //采用远程拉取 github 当前组织下的模板
    let repo = await this.fetchRepo();
    //再通过模板找到版本号
    let tag = await this.fetchTag(repo);
    console.log(repo, tag);
    //下载
    let downloadUrl = await this.download(repo, tag);

    //单独写个类去生成模板

    //编译模板
  }
}

module.exports = Creator;
